/**
 * create by hp
 * date 2020/3/7 12:30
 * @type {string[]}
 */

const log = require('single-line-log').stdout;

export async function execShell(conn: any,
                                shell: Array<String>,
                                logOpen: Boolean = true,
                                callBack?: (str: string) => void) {
  return new Promise((resolve, reject) => {
    conn.shell(async (err, stream) => {
      if (err) return reject(err)
      stream.on('close', function () {
        return resolve()
      }).on('data', function (data) {
        if (callBack) callBack(data.toString())
        if (logOpen) console.log(data.toString());
        log(new Date())
      }).on('end', function () {
        stream.close()
      })
      for (let string of shell) {
        await sleep(0)
        await stream.write(string + "\n")
      }
      stream.end("exit\n")
    })
  })
}

async function sleep(time: number) {
  return new Promise<void>((resolve, reject) => {
    setTimeout(() => {
      return resolve()
    }, time)
  })
}
